var PORT = 3000;

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');
var JsonPath = '';

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
	console.log(pathname);
		 if (!pathname.indexOf('/favicon.ico')) {
            return; 
        };
    var realPath = path.join(path.resolve() , pathname);
    console.log(realPath);
	pathname = realPath;

	if (pathname.charAt(pathname.length - 1) == "/") {
            //如果访问目录
			// 返回目录的目录：
			try{
			JsonPath = '';
			walkJson(filePath);
			JsonPath = JsonPath.substr(0,JsonPath.length-1);
			JsonPath = "[" +  JsonPath  + "]" ;
			//console.log("123" + JsonPath);
			jsonstr = JsonPath;
			// response.writeHead(200,{'Content-Type' : 'text/html'});
			// response.write('<head><meta charset="utf-8"/></head>'); 　
			response.write(jsonstr);
			 response.end();
			 return;
			}
			catch(e)
			{
				console.log('目录访问错误!!！');
			}
            //  pathname += "index.html"; //指定为默认网页
        }
		else
		{
			try {
				fs.readFile( pathname, function (err, data) {        
			 if( err ){
				JsonPath = '';
				walkJson(pathname);
				JsonPath = JsonPath.substr(0,JsonPath.length-1);
				JsonPath = "[" +  JsonPath  + "]" ;
				//console.log("123" + JsonPath);
				//response.writeHead(200,{'Content-Type' : 'text/html'});　
				//response.write('<head><meta charset="utf-8"/></head>'); 
				jsonstr = JsonPath;
				response.end(jsonstr);
			 }else{
				 	//var ast= 'File uploaded successfully';
					//console.log( ast );	
					var lastName = getdir(pathname);
　					response.writeHead(200,{'Content-Type' : 'text/html'});　					
					response.write(data);
					response.end();　
				}
			   });	
		
			} catch(e) 
			{
				console.log('路径访问错误！');
			}
			
		}
   
		
	     
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

//获取后缀名
function getdir(url){
  var arr = url.split('.');
  var len = arr.length;
  return arr[len-1];
}

function walkJson(path){
	var dirList = fs.readdirSync(path);
	dirList.forEach(function(item){
		if(fs.statSync(path + '/' + item).isDirectory()){
			//walkJson(path + '/' + item);
			//var ReFile = getRedir(path + '/' + item );
			JsonPath = JsonPath + "\"" + item + "/\",";			
		}else{
			//var ReFile = getRedir(path + '/' + item);
			JsonPath = JsonPath + "\"" + item + "\",";			
		}			
	});
}
function getRedir(url){
 //console.log(url);
  var filePath = path.resolve() + '\\';
  var arr = url.split(filePath);
  var len = arr.length;
 // console.log(arr[len-1]);
  return arr[len-1];
}
process.on('uncaughtException', function (err) {
  //打印出错误
  console.log(err);
  //打印出错误的调用栈方便调试
  console.log(err.stack);
});